/*!
 * Copyright (c) 2023-present StarDreamNet
 */
(document.loader || (document.loader = [])).push(["shequ", class {
    constructor() {
        this.page = this.getUrlPage(); // 当前页数
        this.postData = null; // 帖子数据
        this.search = this.getSearch(); // 搜索内容
        this.partitionName = this.getPartition(); // 帖子分区名
    };
    init_(require) { // 全局初始化
        const { resize, dateSpanString, pushStateWithSearchParams } = require("index");
        const { loadPostsByData } = require("postlist");

        this.resize = resize;
        this.dateSpanString = dateSpanString;
        this.pushStateWithSearchParams = pushStateWithSearchParams;
        this.loadPostsByData = loadPostsByData.bind(require("postlist"));

        this.getPostData();
        this.getPartitionData();
        this.resetPartitionPosition();
        this.initSearch();
        this.initPartitionStateHistory();
    };

    // —————————————————————————— 帖子&分页 ——————————————————————————
    loadPostStart() { // 加载开始
        $(".app-cards").attr("load", "").html("").append($("<p class='load'>加载中</p>"));
        $(".app-main-pages").html("");
        this.resize();
    };
    loadPostEnd() {  // 加载结束
        $(".app-cards").removeAttr("load", "").find("p.load").remove();
        this.resize();
    };
    loadPostError(msg) { // 加载出错
        this.loadPostEnd();
        $(".app-cards").attr("load", "").attr("error", "").append($("<p>").text(msg || '加载出错'));
        this.resize();
    };
    getPostData() { // 获取数据
        this.loadPostStart();
        if (this.search) {
            this.searchOpen();
            $.ajax('/api/shequ/search_post/' + this.page + "?t=" + Date.now() + "&key_word=" + encodeURIComponent(this.search), {
                contentType: 'application/json',
            }).done((response) => {
                if (response.code == 200) { // 如果状态码为200
                    this.postData = response.data;

                    this.loadPostEnd();
                    this.renderPost();
                    this.renderPages();
                } else {
                    this.loadPostError(response.msg);
                }
            }).fail(() => {
                this.loadPostError();
            });
        } else {
            this.searchClose();
            $.ajax('/api/shequ/get_post_list/' + this.page + '/' + this.partitionName + "?t=" + Date.now(), {
                contentType: 'application/json',
            }).done((response) => {
                if (response.code == 200) { // 如果状态码为200
                    this.postData = response.data;

                    this.loadPostEnd();
                    this.renderPost();
                    this.renderPages();
                } else {
                    this.loadPostError(response.msg);
                }
            }).fail(() => {
                this.loadPostError();
            });
        }
    };
    renderPost() { // 渲染帖子
        var data = this.postData.data;
        var cards = $('.app-cards');
        this.loadPostsByData(data, cards);
        this.resize();
    };
    renderPages() { // 渲染分页
        $(".app-main-pages").html("");

        var page = this.page; // 当前页
        var size = this.postData.size; // 总页数
        var omit = true; // 是否省略

        // 添加向左翻页按钮
        var left = $(`<button class="left">&lt;</button>`)
        left.appendTo($(".app-main-pages"));

        for (let i = 0; i < size; i++) {
            let toadd = false; // 是否要添加页数按钮

            if (i === 0) toadd = true; // 第一页要添加
            if (i === size - 1) toadd = true; // 最后一页要添加
            if (i - page < 2 && i - page > -4) toadd = true; // 如果与当前页的距离小于2，则添加
            if (page < 5 && i < 7) toadd = true; // 如果当前页小于5，则前7页都要添加
            if (page > size - 5 && i > size - 7) toadd = true; // 如果当前页在倒数5页范围内，则倒数7页都要添加

            if (toadd) {
                // 渲染页数按钮
                let button = $(`<button class="${(i + 1) == page ? `active` : ""} page-num">${i + 1}</button>`);
                button.on("click", () => { // 点击事件
                    this.goToTop();
                    this.changePage(Number(i + 1));
                })
                button.appendTo($(".app-main-pages"));
                omit = true;
            } else {
                if (omit) {
                    $(`<button disabled>...</button>`).appendTo($(".app-main-pages"));
                    omit = false;
                }
            }
        }

        // 添加向右翻页按钮
        var right = $(`<button class="right">&gt;</button>`)
        right.appendTo($(".app-main-pages"));

        // 根据条件禁用按钮
        left.prop("disabled", page === 1);
        right.prop("disabled", page === size)

        // 添加点击事件
        left.on("click", () => { // 向左
            this.changePage(this.page - 1);
        })

        right.on("click", () => { // 向右
            this.changePage(this.page + 1);
        })

        this.resize();
    };
    goToTop() { // 回到顶部
        window.scrollTo({
            top: 0
        });
    };
    changePage(page) { // 更改页面
        this.page = Number(page) || 1;
        this.pushStateWithSearchParams({
            p: this.page
        });
        this.getPostData();
    };
    getUrlPage() { // 获取链接中的页面参数
        return Number(new URL(location.href).searchParams.get("p")) || 1;
    };

    // —————————————————————————— 分区加载 ——————————————————————————
    getPartitionData() { // 获取数据
        var loadingText = $("<p>加载中</p>");
        loadingText.appendTo(".app-shequ-partition");

        $.ajax('/api/shequ/get_post_partition/?t=' + Date.now(), {
            contentType: 'application/json',
        }).done(response => {
            loadingText.remove();

            if (response.code == 200) { // 如果状态码为200
                var d = [{
                    id: "all",
                    name: "全部帖子"
                }].concat(response.data);

                for (let va of d) { // 渲染
                    // 电脑端
                    let el = $("<button></button>");
                    el.text(va.name);
                    el.on("click", () => {
                        this.pushStateWithSearchParams({
                            pa: va.id,
                            p: 1
                        });
                        this.updatePartition();
                    })
                    el.attr("pa", String(va.id));
                    $(".app-shequ-partition").append(el);

                    // 移动端
                    let el2 = $("<button></button>");
                    el2.text(va.name);
                    el2.css("minWidth", (14 * va.name.length + 26) + "px")
                    el2.on("click", () => {
                        this.pushStateWithSearchParams({
                            pa: va.id,
                            p: 1
                        });
                        this.updatePartition();
                    })
                    el2.attr("pa", String(va.id));
                    $(".app-main-content-item-mpa").append(el2);
                }

                this.updatePartitionActive();
            } else {
                $(".app-shequ-partition").append($("<p>").text(response.msg || '加载出错'));
            }
        }).fail(() => {
            $(".app-shequ-partition").append("<p>加载出错</p>");
        });
    };
    updatePartitionActive() {
        $(".app-shequ-partition > button, .app-main-content-item-mpa > button").each((_, el) => {
            if (this.partitionName == String($(el).attr("pa"))) $(el).addClass("active")
            else $(el).removeClass("active")
        });
    };
    getPartition() { // 获取分区
        return new URL(location.href).searchParams.get("pa") || "all";
    };
    updatePartition() { // 切换分区
        this.partitionName = this.getPartition();
        this.updatePartitionActive();
        this.changePage(1);
    };
    resetPartitionPosition() { // 重新规划分区栏位置
        var par = $(".app-shequ-partition");
        if ($(window).scrollTop() >= 50) par.addClass("fixed");
        else par.removeClass("fixed");
        requestAnimationFrame(this.resetPartitionPosition.bind(this));
    };
    initPartitionStateHistory() {
        $(window).on('popstate', () => {
            if (this.getPartition() != this.partitionName) {
                this.updatePartition();
            }
        })
    };

    // —————————————————————————— 搜索加载 ——————————————————————————
    initSearch() {
        var input = $(".app-main-content-item-search-input");
        var btn = $(".app-main-content-item-search-btn");
        var back = $(".app-main-content-item-search-back");

        input.val(this.search);

        // 内容更新时，如果为空则禁用按钮
        input.on("input", () => {
            if (input.val() == "") btn.attr("disabled", "");
            else btn.removeAttr("disabled");
        });

        // 按钮点击搜索
        btn.on("click", () => {
            if (input.val() == "") return;
            this.changeSearch(input.val());
        });

        // 在输入框聚集时按下回车也触发搜索
        input.on("keydown", (e) => {
            if (e.keyCode == 13) {
                if (input.val() == "") return;
                this.changeSearch(input.val());
            }
        });

        // 返回按钮点击时清空搜索内容
        back.on("click", () => {
            input.val("");
            this.changeSearch("");
        });
    };
    changeSearch(search) {
        this.search = search;
        this.pushStateWithSearchParams({
            pa: null,
            sr: this.search ? encodeURIComponent(this.search) : null,
            p: 1
        });
        this.updatePartition();
    };
    searchOpen() {
        $(".app-shequ-partition-abs").hide();
        $(".app-main-content-item-mpa").addClass("hide");
        $(".app-main-content-item-search-back").show();
        $(".app-main-content-item-title span").hide();
    };
    searchClose() {
        $(".app-shequ-partition-abs").show();
        $(".app-main-content-item-mpa").removeClass("hide");
        $(".app-main-content-item-search-back").hide();
        $(".app-main-content-item-title span").show();
    };
    getSearch() { // 获取链接中的搜索参数
        return decodeURIComponent(new URL(location.href).searchParams.get("sr") || "") || "";
    };
}])